package cn.tedu.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * mqtt发送者
 * 订单服务 用来发送消息到emqx
 */
@Slf4j
@Component
public class MqttProducer {

    @Autowired
    private MqttClient mqttClient;

    /**
     * 往  topic 发送 消息 message
     * @param topic
     * @param message
     *essage.getBytes()  把字符串换成字节数组byte[]
     */
    public void sendMessage(String topic, String message) {
        //public void publish(String topic, byte[] payload,int qos, boolean retained)
        try {
            //发送消息         哪个主题，消息是啥    “往topic这个主题，发送消息”
            mqttClient.publish(topic, message.getBytes(),0,false);
            //mqttClient 是通过 MqttConfiguration 配置类中 配置好的
        } catch (MqttException e) {
            log.error("给emqx发送消息失败topic:{},message:{}",topic,message,e);
            throw new RuntimeException(e);
        }
    }
}